package com.supermap.desktop.datatopology.CtrlAction;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import com.supermap.data.Dataset;
import com.supermap.data.DatasetType;
import com.supermap.data.DatasetVector;
import com.supermap.data.Datasets;
import com.supermap.data.Datasource;
import com.supermap.data.Datasources;
import com.supermap.data.topology.TopologyProcessingOptions;
import com.supermap.desktop.Application;
import com.supermap.desktop.CommonToolkit;
import com.supermap.desktop.datatopology.DataTopologyProperties;
import com.supermap.desktop.properties.CommonProperties;
import com.supermap.desktop.ui.controls.DataCell;
import com.supermap.desktop.ui.controls.DatasetComboBox;
import com.supermap.desktop.ui.controls.DatasourceComboBox;
import com.supermap.desktop.ui.controls.SmDialog;
import com.supermap.desktop.ui.controls.progress.FormProgress;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JButton;
import javax.swing.border.TitledBorder;
import javax.swing.JLabel;
import javax.swing.JCheckBox;
import javax.swing.JTextField;

public class JDialogTopoBuildRegions extends SmDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JButton buttonMore = new JButton("String_Button_Advance");
	private JButton buttonSure = new JButton("String_Button_OK");
	private JButton buttonQuite = new JButton("String_Button_Cancel");
	private JCheckBox checkboxLinesIntersected = new JCheckBox("String_LinesIntersected");
	private JCheckBox checkboxOvershootsCleaned = new JCheckBox("String_CleanOvershoots");
	private JCheckBox checkboxPseudoNodesCleaned = new JCheckBox("String_CleanPseudoNodes");
	private JCheckBox checkboxAdjacentEndpointsMerged = new JCheckBox("String_MergeAdjacentEndpoints");
	private JCheckBox checkboxDuplicatedLinesCleaned = new JCheckBox("String_CleanDuplicatedLines");
	private JCheckBox checkboxUndershootsExtended = new JCheckBox("String_Label_UndershootsTolerance");
	private JCheckBox checkboxRedundantVerticesCleaned = new JCheckBox("String_RedundantVertices");
	private JLabel labelDatasource = new JLabel("String_Label_Datasource");
	private JLabel labelDataset = new JLabel("String_Label_Dataset");
	private DatasourceComboBox comboBoxDatasource;
	private DatasetComboBox comboBoxDataset;
	private JPanel panelDatasource = new JPanel();
	private JPanel panelTopoProcessingOptions = new JPanel();
	private JPanel panelResultData = new JPanel();
	private JLabel labelResultDatasource = new JLabel("New label");
	private JLabel labelResultDataset = new JLabel("New label");
	private DatasourceComboBox comboBoxResultDatasource;
	private JTextField textFieldResultDataset = new JTextField("BuildRegion");
	private boolean isAdjacentEndpointsMerged = true;
	private boolean isDuplicatedLinesCleaned = true;
	private boolean isLinesIntersected = true;
	private boolean isOvershootsCleaned = true;
	private boolean isPseudoNodesCleaned = true;
	private boolean isRedundantVerticesCleaned = true;
	private boolean isUndershootsExtended = true;
	private transient TopologyProcessingOptions topologyProcessingOptions = new TopologyProcessingOptions();
	private JCheckBox checkBoxtopologyPropress = new JCheckBox();
	private boolean hasDataset;

	public JDialogTopoBuildRegions(JFrame owner, boolean model) {
		super(owner, model);
		initComponents();
		initResources();

	}

	private void initResources() {
		setTitle(DataTopologyProperties.getString("String_TopoRegionTitle"));
		buttonMore.setText(CommonProperties.getString("String_Button_Advance"));
		buttonSure.setText(CommonProperties.getString("String_Button_OK"));
		buttonQuite.setText(CommonProperties.getString("String_Button_Cancel"));
		checkboxLinesIntersected.setSelected(true);
		checkboxLinesIntersected.setText(DataTopologyProperties.getString("String_LinesIntersected"));
		checkboxOvershootsCleaned.setSelected(true);
		checkboxOvershootsCleaned.setText(DataTopologyProperties.getString("String_CleanOvershoots"));
		checkboxPseudoNodesCleaned.setSelected(true);
		checkboxPseudoNodesCleaned.setText(DataTopologyProperties.getString("String_CleanPseudoNodes"));
		checkboxAdjacentEndpointsMerged.setSelected(true);
		checkboxAdjacentEndpointsMerged.setText(DataTopologyProperties.getString("String_MergeAdjacentEndpoints"));
		checkboxDuplicatedLinesCleaned.setSelected(true);
		checkboxDuplicatedLinesCleaned.setText(DataTopologyProperties.getString("String_CleanDuplicatedLines"));
		checkboxUndershootsExtended.setSelected(true);
		checkboxUndershootsExtended.setText(DataTopologyProperties.getString("String_Label_UndershootsTolerance"));
		checkboxRedundantVerticesCleaned.setSelected(true);
		checkboxRedundantVerticesCleaned.setText(DataTopologyProperties.getString("String_RedundantVertices"));
		labelDatasource.setText(CommonProperties.getString("String_Label_Datasource"));
		labelDataset.setText(CommonProperties.getString("String_Label_Dataset"));
		labelResultDatasource.setText(CommonProperties.getString("String_Label_Datasource"));
		labelResultDataset.setText(CommonProperties.getString("String_Label_Dataset"));
		checkBoxtopologyPropress.setText(DataTopologyProperties.getString("String_Topo_Build"));
		checkBoxtopologyPropress.setToolTipText(DataTopologyProperties.getString("String_TopoLineTipsInfo"));

		panelDatasource.setBorder(new TitledBorder(null, CommonProperties.getString("String_ColumnHeader_SourceData"), TitledBorder.LEADING, TitledBorder.TOP,
				null, null));
		panelTopoProcessingOptions.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panelResultData.setBorder(new TitledBorder(null, CommonProperties.getString("String_GroupBox_ResultData"), TitledBorder.LEADING, TitledBorder.TOP,
				null, null));
	}

	/**
	 * 修改textField的内容
	 * 
	 * @param datasource
	 */
	private void initTextFieldName(Datasource datasource) {
		String regionDatasetName = textFieldResultDataset.getText();
		try {
			String availableName = datasource.getDatasets().getAvailableDatasetName(regionDatasetName);
			textFieldResultDataset.setText(availableName);
		} catch (Exception e) {
			Application.getActiveApplication().getOutput().output(e);
		}
	}

	/**
	 * 初始化ComboBox下拉选项
	 */
	private void initComboBoxItem() {
		try {
			Datasources datasources = Application.getActiveApplication().getWorkspace().getDatasources();
			if (null != datasources) {
				comboBoxDatasource = new DatasourceComboBox(datasources);
				comboBoxResultDatasource = new DatasourceComboBox(datasources);
				comboBoxDataset = new DatasetComboBox(new Dataset[0]);
				initTextFieldName(datasources.get(0));
				hasDataset = insertItemToComboBox(datasources.get(0));
				if (!hasDataset) {
					buttonSure.setEnabled(false);
					buttonMore.setEnabled(false);
					checkboxLinesIntersected.setEnabled(false);
					checkboxOvershootsCleaned.setEnabled(false);
					checkboxPseudoNodesCleaned.setEnabled(false);
					checkboxAdjacentEndpointsMerged.setEnabled(false);
					checkboxDuplicatedLinesCleaned.setEnabled(false);
					checkboxUndershootsExtended.setEnabled(false);
					checkboxRedundantVerticesCleaned.setEnabled(false);
				} else {
					buttonSure.setEnabled(true);
					buttonMore.setEnabled(true);
					checkboxLinesIntersected.setEnabled(true);
					checkboxOvershootsCleaned.setEnabled(true);
					checkboxPseudoNodesCleaned.setEnabled(true);
					checkboxAdjacentEndpointsMerged.setEnabled(true);
					checkboxDuplicatedLinesCleaned.setEnabled(true);
					checkboxUndershootsExtended.setEnabled(true);
					checkboxRedundantVerticesCleaned.setEnabled(true);
				}
			}
		} catch (Exception e) {
			Application.getActiveApplication().getOutput().output(e);
		}
	}

	private void initComponents() {
		setType(Type.UTILITY);
		initComboBoxItem();
		setResizable(false);
		setBounds(600, 300, 280, 416);
		GroupLayout groupLayout = new GroupLayout(getContentPane());
		groupLayout.setHorizontalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(
				groupLayout
						.createSequentialGroup()
						.addContainerGap()
						.addGroup(
								groupLayout
										.createParallelGroup(Alignment.TRAILING, false)
										.addComponent(panelResultData, Alignment.LEADING, 0, 0, Short.MAX_VALUE)
										.addGroup(
												Alignment.LEADING,
												groupLayout
														.createParallelGroup(Alignment.TRAILING)
														.addGroup(
																groupLayout.createSequentialGroup().addPreferredGap(ComponentPlacement.RELATED)
																		.addComponent(buttonSure).addPreferredGap(ComponentPlacement.RELATED)
																		.addComponent(buttonQuite))
														.addGroup(
																Alignment.LEADING,
																groupLayout
																		.createParallelGroup(Alignment.LEADING, false)
																		.addComponent(panelTopoProcessingOptions, GroupLayout.DEFAULT_SIZE, 246,
																				Short.MAX_VALUE).addComponent(checkBoxtopologyPropress)
																		.addComponent(panelDatasource, GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE))))
						.addContainerGap(61, Short.MAX_VALUE)));
		groupLayout.setVerticalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(
				groupLayout.createSequentialGroup().addContainerGap()
						.addComponent(panelDatasource, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED).addComponent(checkBoxtopologyPropress).addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(panelTopoProcessingOptions, GroupLayout.PREFERRED_SIZE, 131, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addComponent(panelResultData, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addPreferredGap(ComponentPlacement.UNRELATED)
						.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(buttonSure).addComponent(buttonQuite)).addContainerGap()));
		checkBoxtopologyPropress.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (!checkBoxtopologyPropress.isSelected()) {
					checkboxLinesIntersected.setEnabled(false);
					checkboxOvershootsCleaned.setEnabled(false);
					checkboxPseudoNodesCleaned.setEnabled(false);
					checkboxAdjacentEndpointsMerged.setEnabled(false);
					checkboxDuplicatedLinesCleaned.setEnabled(false);
					checkboxUndershootsExtended.setEnabled(false);
					checkboxRedundantVerticesCleaned.setEnabled(false);
					buttonMore.setEnabled(false);
				} else {
					checkboxLinesIntersected.setEnabled(true);
					checkboxOvershootsCleaned.setEnabled(true);
					checkboxPseudoNodesCleaned.setEnabled(true);
					checkboxAdjacentEndpointsMerged.setEnabled(true);
					checkboxDuplicatedLinesCleaned.setEnabled(true);
					checkboxUndershootsExtended.setEnabled(true);
					checkboxRedundantVerticesCleaned.setEnabled(true);
					buttonMore.setEnabled(true);
				}
			}
		});
		GroupLayout gl_panelResultData = new GroupLayout(panelResultData);
		gl_panelResultData.setAutoCreateContainerGaps(true);
		gl_panelResultData.setAutoCreateGaps(true);

		gl_panelResultData.setHorizontalGroup(gl_panelResultData
				.createParallelGroup()
				.addGroup(
						gl_panelResultData.createSequentialGroup().addComponent(labelResultDatasource, 0, 72, Short.MAX_VALUE)
								.addPreferredGap(ComponentPlacement.RELATED).addComponent(comboBoxResultDatasource, 0, 144, Short.MAX_VALUE))
				.addGroup(
						gl_panelResultData.createSequentialGroup().addComponent(labelResultDataset, 0, 72, Short.MAX_VALUE)
								.addPreferredGap(ComponentPlacement.RELATED).addComponent(textFieldResultDataset, 0, 144, Short.MAX_VALUE)));
		gl_panelResultData.setVerticalGroup(gl_panelResultData.createSequentialGroup()
				.addGroup(gl_panelResultData.createParallelGroup().addComponent(labelResultDatasource).addComponent(comboBoxResultDatasource))
				.addGroup(gl_panelResultData.createParallelGroup().addComponent(labelResultDataset).addComponent(textFieldResultDataset)));
		panelResultData.setLayout(gl_panelResultData);

		GroupLayout gl_panelTopoProcessingOptions = new GroupLayout(panelTopoProcessingOptions);
		gl_panelTopoProcessingOptions.setHorizontalGroup(gl_panelTopoProcessingOptions.createParallelGroup(Alignment.LEADING)
				.addGroup(
						gl_panelTopoProcessingOptions
								.createSequentialGroup()
								.addGroup(
										gl_panelTopoProcessingOptions.createParallelGroup(Alignment.LEADING)
												.addComponent(checkboxLinesIntersected, GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE)
												.addComponent(checkboxOvershootsCleaned, GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE)
												.addComponent(checkboxPseudoNodesCleaned, GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE)
												.addComponent(checkboxAdjacentEndpointsMerged, GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE))
								.addPreferredGap(ComponentPlacement.RELATED)
								.addGroup(
										gl_panelTopoProcessingOptions
												.createParallelGroup(Alignment.LEADING)
												.addComponent(checkboxDuplicatedLinesCleaned, GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE)
												.addComponent(checkboxUndershootsExtended, GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE)
												.addComponent(checkboxRedundantVerticesCleaned, GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE)
												.addGroup(
														gl_panelTopoProcessingOptions.createSequentialGroup()
																.addComponent(buttonMore, GroupLayout.PREFERRED_SIZE, 72, GroupLayout.PREFERRED_SIZE)
																.addContainerGap()))));
		gl_panelTopoProcessingOptions.setVerticalGroup(gl_panelTopoProcessingOptions.createParallelGroup(Alignment.BASELINE).addGroup(
				gl_panelTopoProcessingOptions
						.createSequentialGroup()
						.addGroup(
								gl_panelTopoProcessingOptions
										.createParallelGroup(Alignment.LEADING)
										.addGroup(
												gl_panelTopoProcessingOptions.createSequentialGroup().addComponent(checkboxLinesIntersected)
														.addComponent(checkboxOvershootsCleaned).addComponent(checkboxPseudoNodesCleaned)
														.addComponent(checkboxAdjacentEndpointsMerged))
										.addGroup(
												gl_panelTopoProcessingOptions.createSequentialGroup().addComponent(checkboxDuplicatedLinesCleaned)
														.addComponent(checkboxUndershootsExtended).addComponent(checkboxRedundantVerticesCleaned)
														.addPreferredGap(ComponentPlacement.RELATED).addComponent(buttonMore))).addContainerGap()));
		gl_panelTopoProcessingOptions.setAutoCreateContainerGaps(true);
		gl_panelTopoProcessingOptions.setAutoCreateGaps(true);
		checkboxLinesIntersected.setEnabled(false);
		checkboxOvershootsCleaned.setEnabled(false);
		checkboxPseudoNodesCleaned.setEnabled(false);
		checkboxAdjacentEndpointsMerged.setEnabled(false);
		checkboxDuplicatedLinesCleaned.setEnabled(false);
		checkboxUndershootsExtended.setEnabled(false);
		checkboxRedundantVerticesCleaned.setEnabled(false);
		buttonMore.setEnabled(false);

		panelTopoProcessingOptions.setLayout(gl_panelTopoProcessingOptions);

		GroupLayout gl_panelDatasource = new GroupLayout(panelDatasource);
		gl_panelDatasource.setAutoCreateContainerGaps(true);
		gl_panelDatasource.setAutoCreateGaps(true);

		gl_panelDatasource.setHorizontalGroup(gl_panelDatasource
				.createParallelGroup()
				.addGroup(
						gl_panelDatasource.createSequentialGroup().addComponent(labelDatasource, 0, 72, Short.MAX_VALUE)
								.addPreferredGap(ComponentPlacement.RELATED).addComponent(comboBoxDatasource, 0, 144, Short.MAX_VALUE))
				.addGroup(
						gl_panelDatasource.createSequentialGroup().addComponent(labelDataset, 0, 72, Short.MAX_VALUE)
								.addPreferredGap(ComponentPlacement.RELATED).addComponent(comboBoxDataset, 0, 144, Short.MAX_VALUE)));
		gl_panelDatasource.setVerticalGroup(gl_panelDatasource.createSequentialGroup()
				.addGroup(gl_panelDatasource.createParallelGroup().addComponent(labelDatasource).addComponent(comboBoxDatasource))
				.addGroup(gl_panelDatasource.createParallelGroup().addComponent(labelDataset).addComponent(comboBoxDataset)));
		panelDatasource.setLayout(gl_panelDatasource);
		getContentPane().setLayout(groupLayout);
		buttonMore.addActionListener(new CommonButtonListener());
		buttonQuite.addActionListener(new CommonButtonListener());
		buttonSure.addActionListener(new CommonButtonListener());
		comboBoxDatasource.addActionListener(new CommonButtonListener());
		comboBoxResultDatasource.addActionListener(new CommonButtonListener());
	}

	class CommonButtonListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			JComponent c = (JComponent) e.getSource();
			if (c == buttonSure) {
				boolean isTopoprogress = checkBoxtopologyPropress.isSelected();
				if (isTopoprogress) {
					topologyProcess();
				}
				// 进度条待实现
				topologyBuildRegion();
				dispose();
			}
			if (c == buttonQuite) {
				dispose();
			}
			if (c == buttonMore) {
				openAdvanceDialog(topologyProcessingOptions);
			}
			if (c == comboBoxDatasource) {
				changeComboBoxItem();
			}
			if (c == comboBoxResultDatasource) {
				String datasourceName = comboBoxResultDatasource.getSelectItem();
				Datasource datasource = Application.getActiveApplication().getWorkspace().getDatasources().get(datasourceName);
				initTextFieldName(datasource);
			}
		}

	}

	/**
	 * 改变下拉选项时修改comboBoxDataset的值
	 */
	private void changeComboBoxItem() {
		String datasourceName = comboBoxDatasource.getSelectItem();
		Datasource datasource = Application.getActiveApplication().getWorkspace().getDatasources().get(datasourceName);
		hasDataset = insertItemToComboBox(datasource);
		if (!hasDataset) {
			buttonSure.setEnabled(false);
			buttonMore.setEnabled(false);
			checkboxLinesIntersected.setEnabled(false);
			checkboxOvershootsCleaned.setEnabled(false);
			checkboxPseudoNodesCleaned.setEnabled(false);
			checkboxAdjacentEndpointsMerged.setEnabled(false);
			checkboxDuplicatedLinesCleaned.setEnabled(false);
			checkboxUndershootsExtended.setEnabled(false);
			checkboxRedundantVerticesCleaned.setEnabled(false);
		} else {
			buttonSure.setEnabled(true);
			buttonMore.setEnabled(true);
			checkboxLinesIntersected.setEnabled(true);
			checkboxOvershootsCleaned.setEnabled(true);
			checkboxPseudoNodesCleaned.setEnabled(true);
			checkboxAdjacentEndpointsMerged.setEnabled(true);
			checkboxDuplicatedLinesCleaned.setEnabled(true);
			checkboxUndershootsExtended.setEnabled(true);
			checkboxRedundantVerticesCleaned.setEnabled(true);
		}
	}

	/**
	 * 为comboBoxDataset插入选项
	 * 
	 * @param datasets
	 */
	private boolean insertItemToComboBox(Datasource datasource) {
		comboBoxDataset.removeAllItems();
		int count = 0;
		if (null != datasource) {
			Datasets datasets = datasource.getDatasets();
			for (int i = 0; i < datasets.getCount(); i++) {
				if (datasets.get(i).getType() == DatasetType.LINE || datasets.get(i).getType() == DatasetType.NETWORK) {
					String path = CommonToolkit.DatasetImageWrap.getImageIconPath(datasets.get(i).getType());
					DataCell cell = new DataCell(path, datasets.get(i).getName());
					comboBoxDataset.addItem(cell);
					count++;
				}
			}
		}
		if (0 < count) {
			return true;
		}
		return false;
	}

	/**
	 * 线拓扑处理
	 */
	private void topologyProcess() {
		try {
			String datasetName = comboBoxDataset.getSelectItem();
			String datasourceName = comboBoxDatasource.getSelectItem();
			Datasource datasource = Application.getActiveApplication().getWorkspace().getDatasources().get(datasourceName);
			topologyProcessingOptions.setAdjacentEndpointsMerged(isAdjacentEndpointsMerged);
			topologyProcessingOptions.setDuplicatedLinesCleaned(isDuplicatedLinesCleaned);
			topologyProcessingOptions.setLinesIntersected(isLinesIntersected);
			topologyProcessingOptions.setOvershootsCleaned(isOvershootsCleaned);
			topologyProcessingOptions.setPseudoNodesCleaned(isPseudoNodesCleaned);
			topologyProcessingOptions.setRedundantVerticesCleaned(isRedundantVerticesCleaned);
			topologyProcessingOptions.setUndershootsExtended(isUndershootsExtended);
			// 进度条实现
			FormProgress progress = new FormProgress();
			progress.doWork(new LineTopoCleanCallable(datasetName, topologyProcessingOptions, datasource));

		} catch (Exception e) {
			Application.getActiveApplication().getOutput().output(e);
		}
	}

	/**
	 * 拓扑构面
	 */
	private void topologyBuildRegion() {
		try {
			String datasetName = comboBoxDataset.getSelectItem();
			String datasourceName = comboBoxDatasource.getSelectItem();
			String targetDatasetName = textFieldResultDataset.getText();
			// 进度条实现
			FormProgress progress = new FormProgress();
			progress.doWork(new TopoBuildRegionsCallable(datasourceName, datasetName, targetDatasetName, topologyProcessingOptions));
			dispose();
		} catch (Exception e) {
			Application.getActiveApplication().getOutput().output(e);
		}
	}

	/**
	 * 打开高级参数设置页面
	 * 
	 * @param topologyProcessingOptions
	 */
	private void openAdvanceDialog(TopologyProcessingOptions topologyProcessingOptions) {
		try {
			if (0 < comboBoxDataset.getItemCount()) {
				String datasetName = comboBoxDataset.getSelectItem();
				String datasourceName = comboBoxDatasource.getSelectItem();
				Datasource datasource = Application.getActiveApplication().getWorkspace().getDatasources().get(datasourceName);
				Dataset targetDataset = CommonToolkit.DatasetWrap.getDatasetFromDatasource(datasetName, datasource);
				JDialogTopoAdvance advance = new JDialogTopoAdvance(this, true, topologyProcessingOptions, (DatasetVector) targetDataset, datasource);
				advance.setVisible(true);
			}
		} catch (Exception e) {
			Application.getActiveApplication().getOutput().output(e);
		}
	}

}
